package com.zzr.demo.redis.service.impl;

import com.zzr.demo.redis.service.GroupCountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author: xiaomi
 * @date: 2021/10/8
 * @description: 分组计数器
 */
@Service
@Slf4j
public class GroupCountServiceImpl implements GroupCountService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean init(String groupName, String fieldName) {
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        //前两个参数都是 String 
        opsForHash.put(groupName, fieldName, 0);
        return true;
    }

    @Override
    public long increase(String groupName, String fieldName) {
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        Long increment = opsForHash.increment(groupName, fieldName, 1);
        log.info("key:{},filed:{},num:{}", groupName, fieldName, increment);
        return increment;
    }

    @Override
    public long decrease(String groupName, String fieldName) {
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        Long increment = opsForHash.increment(groupName, fieldName, -1);
        log.info("key:{},filed:{},num:{}", groupName, fieldName, increment);
        return increment;
    }
}
